package com.ma.chapter8.jdkpool;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName TestSchedule
 * @Author: mayongqiang
 * @DATE 2022/3/22 20:58
 * @Description: 任务调度 每周四18：00：00 定时执行任务
 */
@Slf4j(topic = "m.TestSchedule")
public class TestSchedule {
    public static void main(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        // 任务 initialDelay初始时间(当前时间和周四时间的时间差)   2、每周间隔时间  3、时间单位
        long period = 1000 * 60 * 60 * 24 * 7;
        // 当前时间
        LocalDateTime now = LocalDateTime.now();
        // 周四 18:00:00
        LocalDateTime thursday =

                now.with(DayOfWeek.THURSDAY).withHour(18).withMinute(0).withSecond(0).withNano(0);
        if (now.compareTo(thursday) >= 0) {
            thursday = thursday.plusWeeks(1);
        }
        // 计算时间差，即延时执行时间
        long initialDelay = Duration.between(
                now, thursday).toMillis();
        pool.scheduleAtFixedRate(() -> {
            log.debug("running...");
        }, initialDelay, period, TimeUnit.SECONDS);
    }
}
